#include "CInput.h"

#pragma region Constructor & Destructor

CInput::CInput(void)
{
}


CInput::~CInput(void)
{
	if(m_input != NULL)
	{
		m_input->Release();
	}
	KillKeyboard();
	KillMouse();
}

CInput::CInput(HWND hWnd)
{
	CreateInterface();
	Setting(hWnd);
}

#pragma endregion

#pragma region Methods

void CInput::CreateInterface()
{
	// Keyboard
	HRESULT result= DirectInput8Create(
		GetModuleHandle(NULL),
		DIRECTINPUT_VERSION,
		IID_IDirectInput8,
		(void**)&m_input,
		NULL);

	if(result != D3D_OK)
	{
		MessageBox(NULL,"Create DirectInput - Failed","Error", MB_OK | MB_ICONERROR);
		return;
	}

	result = m_input->CreateDevice(
		GUID_SysKeyboard,
		&m_keyboard,
		NULL);
	if(result != D3D_OK)
	{
		MessageBox(NULL,"Create Keyboard - Failed","Error",MB_OK | MB_ICONERROR);

		return;
	}

	// Mouse

	result = m_input->CreateDevice(
		GUID_SysMouse,
		&m_mouse,
		NULL);
	if(result != D3D_OK)
	{
		MessageBox(NULL,"Create Mouse - Failed","Error", MB_OK | MB_ICONERROR);
		return;
	}

	// Zero Fill the keyPressState
	for(int i = 0; i<256;i++)
	{
		m_keyState[i] = 0;
		m_buffer[i] = 0;
	}

}

void CInput::Setting(HWND hWnd)
{
	HRESULT result = m_keyboard->SetDataFormat(&c_dfDIKeyboard);
	if(result != D3D_OK)
	{
		return;
	}

	result = m_keyboard->SetCooperativeLevel(hWnd,DISCL_NONEXCLUSIVE | DISCL_BACKGROUND);
	if(result != D3D_OK)
		return;

	result = m_keyboard->Acquire();
	if(result != D3D_OK)
		return;

	// Mouse

	result = m_mouse->SetDataFormat(&c_dfDIMouse);
	if(result != D3D_OK)
	{
		return;
	}

	result = m_mouse->SetCooperativeLevel(hWnd, DISCL_NONEXCLUSIVE | DISCL_BACKGROUND);
	if(result != D3D_OK)
		return;

	result = m_mouse->Acquire();
	if(result != D3D_OK)
	{
		return;
	}
}

HRESULT CInput::GetKeyboardState()
{
	return m_keyboard->GetDeviceState(sizeof(m_buffer),(LPVOID)&m_buffer);
}

HRESULT CInput::GetMouseState()
{
	return m_mouse->GetDeviceState(sizeof(DIMOUSESTATE),(LPVOID)&m_mouse_state);
}

bool CInput::KeyDown(int key)
{
	if(m_buffer[key] & 0x80)
		return true;
	else
		return false;
}

bool CInput::KeyUp(int key)
{
	return !KeyDown(key);
}

bool CInput::KeyPressed(int key)
{
	return true;
}

void CInput::KillKeyboard()
{
	if(m_keyboard != NULL)
	{
		m_keyboard->Unacquire();
		m_keyboard->Release();
		m_keyboard = NULL;
	}
}

void CInput::KillMouse()
{
	if(m_mouse != NULL)
	{
		m_mouse->Unacquire();
		m_mouse->Release();
		m_mouse = NULL;
	}
}

#pragma endregion 